package com.example.shushiyunsst.fragment.main.mine

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.example.library_common.album.Album
import com.example.library_common.album.view.grid_view.adapter.CommAdapter
import com.example.library_common.album.view.grid_view.adapter.XQuickViewHolder
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.glidmodule.GlideApp
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.SoundPoolHelper
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_BALANCE_INFO
import com.example.library_common.utils.even.TO_REFRESH_USER_INFO
import com.example.library_common.utils.upload_file.UploadFileWorker
import com.example.library_common.view.bottombar.BottomBorInfo
import com.example.shushiyunsst.MainActivity
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.MineFragmentLayoutBinding
import com.example.shushiyunsst.fragment.UPDATE_TYPE_USER_LOGO
import com.example.shushiyunsst.fragment.getUserInfo
import com.example.shushiyunsst.fragment.signOut
import com.example.shushiyunsst.util.*
import com.example.wallet.bean.BalanceInfoBean
import com.example.wallet.bean.UserInfo
import com.example.wallet.db.BalanceInfoManager
import com.example.wallet.db.UserInfoManager
import com.example.wallet.utils.UserInfoTempleHolder
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.OnSelectListener
import org.greenrobot.eventbus.EventBus

class MineFragment : BaseDataBindingFragment<MineFragmentLayoutBinding>(), BottomBorInfo,
    View.OnClickListener {

    companion object {
        fun newInstance(): MineFragment {
            val args = Bundle()

            val fragment = MineFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport=false
    }

    override fun layoutId() = R.layout.mine_fragment_layout

    override var icon = R.drawable.ic_mine

    override fun refreshData() {
        getUserInfo(_mActivity)
    }

    override var title = R.string.mine

    private var mOrderAdapter: CommAdapter<OrderConfigBean>? = null

    private var mServiceAdapter: CommAdapter<ConfigBean>? = null

    private var mUploadFileWorker: UploadFileWorker? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewBinder.onViewClick = this

        mOrderAdapter =
            object : CommAdapter<OrderConfigBean>(_mActivity, R.layout.mine_order_fragment) {
                override fun convert(
                    holder: XQuickViewHolder?,
                    item: OrderConfigBean?,
                    position: Int
                ) {
                    holder?.setText(R.id.title_template, item?.title ?: 0)
                        ?.setImageResource(R.id.icon, item?.icon ?: 0)
                        ?.setOnClickListener {
                            if ((item?.path ?: "").isNotEmpty()) {
                                ARouter.getInstance()
                                    .build(item?.path)
                                    .withInt(PAGE_INDEX_OF, item?.pageIndexOf ?: -1)
                                    .startNavigation(this@MineFragment)
                            }
                        }
                }

            }

        viewBinder.orderGridLayout.setAdapter(mOrderAdapter, lifecycle)
        mOrderAdapter?.addAll(ORDER_CONFIG_LIST)
        viewBinder.orderGridLayout.setGridSpan(ORDER_CONFIG_LIST.size)
        viewBinder.orderGridLayout.maxItem=ORDER_CONFIG_LIST.size

        mServiceAdapter =
            object : CommAdapter<ConfigBean>(_mActivity, R.layout.mine_service_fragment) {
                override fun convert(holder: XQuickViewHolder?, item: ConfigBean?, position: Int) {
                    holder?.setText(R.id.title_template, item?.title ?: 0)
                        ?.setImageResource(R.id.icon, item?.icon ?: 0)
                        ?.setOnClickListener {

                            if (item?.title==R.string.shou_kuan){
                                val userInfoManager = UserInfoManager.userInfoManager
                                val userInfoWrapper = userInfoManager.getUserInfoWrapper()
                                val userInfo = userInfoWrapper?.userInfo
                                if (userInfo?.checkStatusIdcard == UserInfo.unSubmit
                                    || userInfo?.checkStatusIdcard == UserInfo.checkedNot
                                ) {
                                    Toast.makeText(_mActivity, "请先实名审核", Toast.LENGTH_SHORT).show()
                                    ARouter.getInstance()
                                        .build(IDENTIFY_VERIFY)
                                        .startNavigation(this@MineFragment)

                                }else if (userInfo?.checkStatusIdcard == UserInfo.checking) {
                                    Toast.makeText(_mActivity, "正在实名审核中，请稍后", Toast.LENGTH_SHORT).show()
                                }else{
                                    ARouter.getInstance()
                                        .build(item.path)
                                        .startNavigation(this@MineFragment)
                                }

                            }else if ((item?.path ?: "").isNotEmpty()) {
                                ARouter.getInstance()
                                    .build(item?.path)
                                    .startNavigation(this@MineFragment)
                            }
                        }
                }

            }

        viewBinder.mServiceGridLayout.setAdapter(mServiceAdapter, lifecycle)
        mServiceAdapter?.addAll(SERVICE_CONFIG_LIST)

//        val signOut:TextView=view.findViewById(R.id.sign_out)
//        signOut.setOnClickListener { signOut()  }


    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.myOrderTv -> {
//                SoundPoolHelper.play(R.raw.beep)
                ARouter.getInstance()
                    .build(MY_ORDER_LIST)
                    .startNavigation(this)
            }
            R.id.verifyStatus -> {
                val userInfoManager = UserInfoManager.userInfoManager
                val userInfoWrapper = userInfoManager.getUserInfoWrapper()
                val userInfo = userInfoWrapper?.userInfo
                if (userInfo?.checkStatusIdcard == UserInfo.unSubmit
                    || userInfo?.checkStatusIdcard == UserInfo.checkedYes
                    || userInfo?.checkStatusIdcard == UserInfo.checkedNot
                ) {
                    ARouter.getInstance()
                        .build(IDENTIFY_VERIFY)
                        .startNavigation(this)
                }
                if (userInfo?.checkStatusIdcard == UserInfo.checking) {
                    Toast.makeText(_mActivity, "正在实名审核中，请稍后", Toast.LENGTH_SHORT).show()
                }
            }
            R.id.sign_out -> {
                signOut()
            }

            R.id.ic_copy_icon -> {
                val userInfoManager = UserInfoManager.userInfoManager
                val userInfoWrapper = userInfoManager.getUserInfoWrapper()
                val userInfo = userInfoWrapper?.userInfo
                clipboard("", (userInfo?.invitationCode ?: ""))
            }

            R.id.avatar -> {
                if (mUploadFileWorker != null) {
                    Toast.makeText(_mActivity, "图片正在上传", Toast.LENGTH_SHORT).show()
                    return
                }
                Album.getInstance()
                    .singleImage()
                    .onSuccess {
                        if (it.isNotEmpty()) {

                            val mutableListOf = mutableListOf<String>()

                            mutableListOf.add(it[0].path)
                            mUploadFileWorker=UploadFileWorker()
                            mUploadFileWorker?.setListener(object :
                                UploadFileWorker.UpLoadOverListener {
                                override fun onUpLoadOver(res: List<String>) {
//                                    mUploadFileWorker = null
                                    onSending(res)
                                }
                            })?.doWork(mutableListOf)
                        }
                    }
                    .onFailed { _, msg ->
                        Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                    }
                    .execute(childFragmentManager)
            }

            R.id.nickNameTv->{
                start(UpDataUSerInfoFragment.newInstance())
            }

        }
    }

    private fun onSending(res: List<String>) {
        if (res.isEmpty()) {
            mUploadFileWorker = null
            Toast.makeText(_mActivity, "图片上传失败", Toast.LENGTH_SHORT).show()
            return
        }
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val maps = mapOf(
            "uid" to userInfo?.uid,
            "updateType" to UPDATE_TYPE_USER_LOGO,
            "valueStr" to res[0]
        )
        RestClient.builder()
            .url(R.string.updateUserInfo)
            .raw(JSON.toJSONString(maps))
            .success {
                mUploadFileWorker=null
                getUserInfo(_mActivity)
            }.error { _, msg ->
                mUploadFileWorker = null
                Toast.makeText(_mActivity,msg,Toast.LENGTH_SHORT).show()
            }
            .failure {
                mUploadFileWorker = null
            }
            .build()
            .post()
    }

//    override fun onLazyInitView(savedInstanceState: Bundle?) {
//        super.onLazyInitView(savedInstanceState)
//        SoundPoolHelper.play(R.raw.beep)
//    }

    override fun handMessage(msg: MessageWrap?) {
        super.handMessage(msg)
        if (msg?.message == TO_REFRESH_USER_INFO) {
            val userInfoManager = UserInfoManager.userInfoManager
            val userInfoWrapper = userInfoManager.getUserInfoWrapper()
            val userInfo = userInfoWrapper?.userInfo
            viewBinder.userInfo = userInfo
            viewBinder.userInfoTemple= UserInfoTempleHolder.getUserInfoTemple()
            Log.d("handMessage", "handMessage: ${UserInfoTempleHolder.getUserInfoTemple().toString()}")
            GlideApp.with(this)
                .load(userInfo?.userLogo)
                .placeholder(R.mipmap.trees_er)
                .into(viewBinder.avatar)

//            Log.d("onViewCreated", "onViewCreated: ${JSON.toJSONString(userInfo)}")
        }

    }


}